package com.file.upload.controller;

import com.file.upload.dto.ChunkUploadDTO;
import com.file.upload.dto.FileUploadDTO;
import com.file.upload.dto.FileUploadResultDTO;
import com.file.upload.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description
 * @Author lhj
 * @Date 2025/4/23 21:30
 */
@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileUploadController {

    private final FileUploadService fileUploadService;

    public FileUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    /**
     * 初始化文件上传
     */
    @PostMapping("/upload/init")
    public ResponseEntity<FileUploadResultDTO> initUpload(@RequestBody FileUploadDTO fileUploadDTO) {
        log.info("初始化文件上传: {}", fileUploadDTO);
        FileUploadResultDTO result = fileUploadService.initFileUpload(fileUploadDTO);
        return ResponseEntity.ok(result);
    }

    /**
     * 上传文件分片
     */
    @PostMapping("/upload/chunk")
    public ResponseEntity<Boolean> uploadChunk(
            @RequestParam("fileId") String fileId,
            @RequestParam("chunkNumber") Integer chunkNumber,
            @RequestParam("file") MultipartFile file) {
        log.info("上传文件分片: fileId={}, chunkNumber={}", fileId, chunkNumber);

        ChunkUploadDTO chunkUploadDTO = new ChunkUploadDTO();
        chunkUploadDTO.setFileId(fileId);
        chunkUploadDTO.setChunkNumber(chunkNumber);
        chunkUploadDTO.setFile(file);

        boolean success = fileUploadService.uploadChunk(chunkUploadDTO);
        return ResponseEntity.ok(success);
    }

    /**
     * 合并文件分片
     */
    @PostMapping("/upload/merge")
    public ResponseEntity<Boolean> mergeChunks(@RequestParam("fileId") String fileId) {
        log.info("合并文件分片: fileId={}", fileId);
        boolean success = fileUploadService.mergeChunks(fileId);
        return ResponseEntity.ok(success);
    }

    /**
     * 检查文件上传状态
     */
    @GetMapping("/upload/status")
    public ResponseEntity<FileUploadResultDTO> checkUploadStatus(@RequestParam("fileId") String fileId) {
        log.info("检查文件上传状态: fileId={}", fileId);
        FileUploadResultDTO result = fileUploadService.checkFileUploadStatus(fileId);
        return ResponseEntity.ok(result);
    }
}
